package com.service.impl;

import com.dao.PermissionDao;
import com.dao.RoleDao;
import com.pojo.Permission;
import com.service.PermissionService;
import com.util.ConstUtils;
import com.vo.PermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author mornd
 * @date 2020/11/13 - 14:12
 */
@Service
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RoleDao roleDao;
    public List<Permission> findPermission(PermissionVo permissionVO) {
        return permissionDao.findPermission(permissionVO);
    }

    //添加permission
    public int addPermission(Permission permission) {
        if(permission.getPid() == null){
            permission.setPid(0);
            permission.setHref("/");
        }
        //如果为菜单，则不需提交权限编码
        if(permission.getType().equals("menu")){
            permission.setPermissionCode(null);
        }
        //默认打开方式
        permission.setTarget("_self");
        int count = permissionDao.addPermission(permission);
        //默认添加的菜单超级管理员可直接访问
        if(count > 0){
            roleDao.addRolePermission(Arrays.asList(permission.getId()), ConstUtils.SUPERADMIN_ID);//超级管理员添加菜单权限
            roleDao.addRolePermission(Arrays.asList(permission.getId()),ConstUtils.ADMIN_ID);//管理员添加菜单权限
        }
        return count;
    }

    public int updatePermission(Permission permission) {
        if(permission.getPid() == null){
            permission.setPid(0);
            permission.setHref("/");
        }
        //如果为菜单，则不需提交权限编码
        if(permission.getType().equals("menu")){
            permission.setPermissionCode(null);
        }
        return permissionDao.updatePermission(permission);
    }

    //估计id删除菜单
    public boolean deletePermission(Integer permissionId) {
        try {
            permissionDao.deleteRolePermission(permissionId);
            permissionDao.deletePermission(permissionId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public List<Permission> findPermissionByRoleId(Integer RoleId) {
        return permissionDao.findPermissionByRoleId(RoleId);
    }

    public List<Permission> findPermissionListByUserId(Integer userId) {
        //默认只查菜单不查权限
        String type = "menu";
        return permissionDao.findPermissionListByUserId(userId,type);
    }
}
